import router from "@/router";
import { useUserStore, useUserStoreHook } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";

import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({ showSpinner: false }); // 进度条

const permissionStore = usePermissionStoreHook();

// 白名单路由
const whiteList = ["/login"];

router.beforeEach(async (to, from) => {
  NProgress.start();
  const store = useUserStore()
  const hasToken = store.userInfo.token
  console.log(hasToken);

  if (hasToken) {
    if (to.path === "/login") {
      // 如果已登录，跳转首页
      return "/"
      NProgress.done();
    } else {
      // const userStore = useUserStoreHook();
      return
      // const hasRoles = userStore.roles && userStore.roles.length > 0;
      // if (hasRoles) {
      //   // 未匹配到任何路由，跳转404
      //   if (to.matched.length === 0) {
      //    return from.name ? { name: from.name } : "/404";
      //   } else {
      //     return
      //   }
      // } else {
      //   try {
      //     // const { roles } = await userStore.getInfo();
      //     // const accessRoutes = await permissionStore.generateRoutes(roles);
      //     accessRoutes.forEach((route) => {
      //       router.addRoute(route);
      //     });
      //     return ({ ...to, replace: true });
      //   } catch (error) {
      //     // 移除 token 并跳转登录页
      //     await userStore.resetToken();
      //     return `/login?redirect=${to.path}`
      //   }
      // }
    }
  } else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
     return
    } else {
     return `/login?redirect=${to.path}`
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
